package cn.icanci.loopstack.rec.common.utils;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @author icanci
 * @since 1.0 Created in 2022/11/15 21:38
 */
public class PropertiesUtil {
    /**
     * The constant confProperties.
     */
    private static Properties confProperties;

    /**
     * 初始化
     *
     * @param classLoader classLoader
     * @param sourcePath sourcePath
     */
    private static void init(ClassLoader classLoader, String sourcePath) {
        if (confProperties == null) {
            confProperties = new Properties();

            try (InputStream in = classLoader.getResourceAsStream(sourcePath)) {
                confProperties.load(in);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * Get string.
     *
     * @param classLoader 类加载器
     * @return the string
     */
    public static Map<String, String> getPropertyMap(ClassLoader classLoader, String sourcePath) {
        // 初始化加载
        init(classLoader, sourcePath);

        Map<String, String> propertyMap = new HashMap<>();
        for (Map.Entry<Object, Object> next : confProperties.entrySet()) {
            propertyMap.put((String) next.getKey(), (String) next.getValue());
        }
        return propertyMap;
    }
}
